package com.shushan.service;

import android.app.KeyguardManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.android.fgchecker.AppChecker;
import com.shushan.home.TabHomeActivity;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.util.SystemUtils;

/**
 * @ClassName: LockOutRTAService
 * @Desciption: 锁屏滑动去其他应用的监听
 * @author: yichaohua
 * @date: 2018-11-29
 */
public class LockOutRTAService extends Service {

    private final static String TAG = "LockOutRTAService";

    private AppChecker appChecker;

    @Override
    public void onCreate() {
        super.onCreate();

        Log.i(TAG, "onCreate()");

        startChecker();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        Log.i(TAG, "onDestroy()");

        stopChecker();
    }

    private void startChecker() {
        appChecker = new AppChecker();
        appChecker.when(getPackageName(), new AppChecker.Listener() {
            @Override
            public void onForeground(String packageName) {
                KeyguardManager mKeyguardManager = (KeyguardManager) BabyApplication.getInstance().getSystemService(Context.KEYGUARD_SERVICE);
                boolean isLock = mKeyguardManager.inKeyguardRestrictedInputMode();

                Log.i(TAG, "Our app is in the foreground. isLock=" + isLock);
                if(!isLock){
                    stopSelf();
                }
            }
        })
        .whenOther(new AppChecker.Listener() {
            @Override
            public void onForeground(String packageName) {
                Log.i(TAG, "onForeground packageName=" + packageName);

                SystemUtils.sendForegActivity(BabyApplication.getInstance(), TabHomeActivity.class);
            }
        })
        .timeout(3000)
        .start(this);
    }

    private void stopChecker() {
        appChecker.stop();
    }
}
